//
//  TDYuDingDetailC.m
//  TBRentClient
//
//  Created by tonbright on 2018/6/11.
//  Copyright © 2018年 tonbright. All rights reserved.
//

#import "TDYuDingDetailC.h"

#import "TDYuDingCarDescCell.h"
#import "TDYuDingCarTimeCell.h"
#import "TDYuDingDriverMessageCell.h"
#import "TDYuDingTryDriveQuanCell.h"
#import "TDYuDingTryDriveLawCell.h"
#import "TDYuDingCarSectionHeadView.h"

#import "TDTryDirveQuanC.h"
#import "TDCheckPayC.h"
#import "TDIdCardMessageGetC.h"
#import "TDIsPickCarInstore.h"
#import "YXDateHelpObject.h"
#import "NetWorkRequest.h"
#import "TDCarSourceModel.h"
#import "TDYuDingDetailModel.h"
#import "TBRMineModel.h"

#import "TDCalendaViewShowC.h"

@interface TDYuDingDetailC ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property(nonatomic,assign)CGFloat historyY;

@property (nonatomic,strong)TDYuDingDetailModel *yuDingDetailModel;
@property (nonatomic,strong)TBRMineModel *shareMineInfoModel;
@property (nonatomic, assign) BOOL isAgreeLaw;

@property (nonatomic,copy)NSString *isPickInstore;//是否门店取车
@property (nonatomic,strong)TBROnCarPlaceModel *onPlaceModel;

@property (weak, nonatomic) IBOutlet UILabel *lbe_basePrice;

@property (nonatomic,strong)TDTryDriveQuanModel *trySelDriveQuanModel;

@property (weak, nonatomic) IBOutlet UIButton *btn_yuding;

@end

@implementation TDYuDingDetailC

- (void)viewDidLoad {
    [super viewDidLoad];
    _isPickInstore = @"1";
    [self setupUI];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    [self loadData];

}

- (IBAction)navBtnClick:(UIButton *)sender {
        [self.navigationController popViewControllerAnimated:YES];
}

- (void)setupUI {
    _btn_yuding.layer.cornerRadius = 5;
    _btn_yuding.layer.masksToBounds = YES;
    //设置导航条
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [UIView new];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDYuDingCarDescCell" bundle:nil] forCellReuseIdentifier:@"TDYuDingCarDescCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDYuDingCarTimeCell" bundle:nil] forCellReuseIdentifier:@"TDYuDingCarTimeCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDYuDingDriverMessageCell" bundle:nil] forCellReuseIdentifier:@"TDYuDingDriverMessageCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDYuDingTryDriveQuanCell" bundle:nil] forCellReuseIdentifier:@"TDYuDingTryDriveQuanCellId"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TDYuDingTryDriveLawCell" bundle:nil] forCellReuseIdentifier:@"TDYuDingTryDriveLawCellId"];
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, -10, 0, -10)];
    }
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100;
}


//区头跟随移动
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat sectionHeaderHeight = 72;
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    } else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
    
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (_historyY+20<targetContentOffset->y)
    {
        //表示是向下滑动
        [self setTabBarHidden:YES];
    }
    else if(_historyY-20>targetContentOffset->y)
    {
        //表示是向上面滑动
        [self setTabBarHidden:NO];
    }
    _historyY=targetContentOffset->y;
}

- (void)setTabBarHidden:(BOOL)hidden
{
    UIView *tab = self.tabBarController.view;
    CGRect  tabRect = self.tabBarController.tabBar.frame;
    if ([tab.subviews count] < 2) {
        return;
    }
    UIView *view;
    if ([[tab.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]]) {
        view = [tab.subviews objectAtIndex:1];
    } else {
        view = [tab.subviews objectAtIndex:0];
    }
    
    if (hidden) {
        view.frame = tab.bounds;
        tabRect.origin.y=[[UIScreen mainScreen]bounds].size.height+self.tabBarController.tabBar.frame.size.height;
    } else {
        view.frame = CGRectMake(tab.bounds.origin.x, tab.bounds.origin.y, tab.bounds.size.width, tab.bounds.size.height);
        tabRect.origin.y=[[UIScreen mainScreen] bounds].size.height-self.tabBarController.tabBar.frame.size.height;
    }
    
    [UIView animateWithDuration:0.5f animations:^{
        self.tabBarController.tabBar.frame=tabRect;
    }completion:^(BOOL finished) {
        
    }];
    
}


// MARK: - 预定按钮点击时间
- (IBAction)yuDingBtnClick:(UIButton *)sender {
    
    // MARK: - 判断当前信息是否验证成功
//    if (![self.shareMineInfoModel.idstatus isEqual:@"1"]) {
//        self.noticeText = @"请先上传驾驶员详细信息";
//        return;
//    }
    if (!self.isAgreeLaw) {
        self.noticeText = @"请先同意试驾条款";
        return;
    }
    
    TDCheckPayC *checkPayC = [[TDCheckPayC alloc] init];
    checkPayC.yuDingDetailModel = self.yuDingDetailModel;
    checkPayC.detailCarModel = self.detailCarModel;
    checkPayC.trySelDriveQuanModel = self.trySelDriveQuanModel;
    checkPayC.onPlaceModel = self.onPlaceModel;
    
    [self.navigationController pushViewController:checkPayC animated:YES];
}



#pragma mark - 返回组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

#pragma mark - 返回行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 6;
}

#pragma mark - 返回每行内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    //自定义cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[self getIdentifier:indexPath] forIndexPath:indexPath];
    [self setupCell:cell indexPath:indexPath];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 125;
    }else if (indexPath.row == 5) {
        return 130;
    }
    return 78;
}

- (NSString *)getIdentifier:(NSIndexPath *)indexPath {
    NSString *iden = @"TDYuDingCarDescCellId";
    if (indexPath.row == 0) {
        iden = @"TDYuDingCarDescCellId";
    }else if(indexPath.row == 1) {
        iden = @"TDYuDingCarTimeCellId";

    }else if (indexPath.row == 5) {
        iden = @"TDYuDingTryDriveLawCellId";
    }else {
        iden = @"TDYuDingDriverMessageCellId";
    }
    return iden;
}

- (void)setupCell:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 5) {
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    if (indexPath.row == 0) {
        TDYuDingCarDescCell *yuDingCarDescCell = (TDYuDingCarDescCell *)cell;
        yuDingCarDescCell.lbe_brandnm.text = [NSString stringWithFormat:@"%@ %@",_yuDingDetailModel.brandnm,_yuDingDetailModel.seriesnm];
        yuDingCarDescCell.lbe_typenm.text = _yuDingDetailModel.typenm;
        NSString *imgStr = [NSString stringWithFormat:@"http://121.40.92.131/deepdriving/%@",_yuDingDetailModel.carimageurl];
        [yuDingCarDescCell.imv_carImg sd_setImageWithURL:[NSURL URLWithString:imgStr] placeholderImage:[UIImage imageNamed:@"car"]];
    }else if(indexPath.row == 1) {
        TDYuDingCarTimeCell *yuDingCarTimeCell = (TDYuDingCarTimeCell *)cell;
        yuDingCarTimeCell.lbe_startTime.text = _yuDingDetailModel.planpickuptimeShow;
        yuDingCarTimeCell.lbe_endTime.text = _yuDingDetailModel.planreturntimeShow;
    }else if (indexPath.row == 5) {
        TDYuDingTryDriveLawCell *yuDingTryDriveLawCell = (TDYuDingTryDriveLawCell *)cell;
        __weak typeof(self) weakSelf = self;
        yuDingTryDriveLawCell.yuDingTryDriveLawCellBlock = ^{
            weakSelf.isAgreeLaw = YES;
        };
    }else {
        TDYuDingDriverMessageCell *yuDingDriverMessageCell = (TDYuDingDriverMessageCell *)cell;
        if (indexPath.row == 2) {
            yuDingDriverMessageCell.lbe_desc.text = @"驾驶员信息(必填)";
            if ([_shareMineInfoModel.idstatus isEqualToString:@"1"]) {
                yuDingDriverMessageCell.lbe_detail.text = @"已填写";
            }else {
                yuDingDriverMessageCell.lbe_detail.text = @"增加";
            }
        }else if (indexPath.row == 3) {
            yuDingDriverMessageCell.lbe_desc.text = @"试驾券";
            if (self.trySelDriveQuanModel) {
                yuDingDriverMessageCell.lbe_detail.text = [NSString stringWithFormat:@"-¥ %@",_yuDingDetailModel.totaldiscount];
                
            }else {
                yuDingDriverMessageCell.lbe_detail.text = @"增加";
            }
        }
        else if (indexPath.row == 4) {
            yuDingDriverMessageCell.lbe_desc.text = @"选择服务";
            if ([_yuDingDetailModel.pickuptype isEqualToString:@"1"]) {
                yuDingDriverMessageCell.lbe_detail.text = @"自取";
            }else {
                yuDingDriverMessageCell.lbe_detail.text = @"送车上门";
            }
        }
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    TDYuDingCarSectionHeadView *headView = [TDYuDingCarSectionHeadView yuDingCarSectionHeadView];
    headView.frame = CGRectMake(0, 0, Width-20, 74);
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 74;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 1) {
        TDCalendaViewShowC *calendaViewShowC = [[TDCalendaViewShowC alloc] init];
        [self.navigationController pushViewController:calendaViewShowC animated:YES];
    }
    if (indexPath.row == 2) {
        TDIdCardMessageGetC *idCardMessageGetC = [[TDIdCardMessageGetC alloc] init];
        idCardMessageGetC.shareMineInfoModel = self.shareMineInfoModel;
        [self.navigationController pushViewController:idCardMessageGetC animated:YES];
    }else if (indexPath.row == 3) {
        TDTryDirveQuanC *tryDirveQuanC = [[TDTryDirveQuanC alloc] init];
        tryDirveQuanC.allCanSelArray = self.yuDingDetailModel.couponlist;
        tryDirveQuanC.isFromCal = YES;
        __weak typeof(self) weakSelf = self;
        tryDirveQuanC.tryDirveQuanCSaveBlock = ^(TDTryDriveQuanModel *tryDriveQuanModel) {
            weakSelf.trySelDriveQuanModel = tryDriveQuanModel;
            [weakSelf.tableView reloadData];

        };
        [self.navigationController pushViewController:tryDirveQuanC animated:YES];
    }else if (indexPath.row == 4){
        TDIsPickCarInstore *isPickCarInstore = [[TDIsPickCarInstore alloc] init];
        isPickCarInstore.isPickInstore = self.isPickInstore;
        __weak typeof(self) weakSelf = self;
        isPickCarInstore.isPickCarInstoreBlock = ^(NSString *isPickInstore, TBROnCarPlaceModel *onPlaceModel) {
            weakSelf.isPickInstore = isPickInstore;
            weakSelf.onPlaceModel = onPlaceModel;
        };
        
        [self.navigationController pushViewController:isPickCarInstore animated:YES];
    }
}



// MARK: - 加载数据
- (void)loadData {
    [self loadLocalData];
    [self loadNetData];
}
// MARK: - 本地数据
- (void)loadLocalData {
    NSString *title = @"车辆详细车辆详细车";
//    CGFloat contentWidth = [UILabel calllHeightWithContent:title andLineNumber:0 andFont:[UIFont systemFontOfSize:14] andWidth:Width-50];
    
}

// MARK: - 获取网络数据-----
- (void)loadNetData {
    NSString *currentDateStr = [[YXDateHelpObject manager] getCurentTime:@"yyyy-MM-dd" dateN:[NSDate date]];
    NSString *tmpStartStr = [self.selDateModel.yearStr stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    NSString *tmpEndStr = [self.selDateModel.yearEndStr stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
    
    
    NSString *startTimeStr = [NSString stringWithFormat:@"%@ %@:00",tmpStartStr,_selDateModel.startHourStr];
    NSString *endTimeStr = [NSString stringWithFormat:@"%@ %@:00",tmpEndStr,_selDateModel.endHourStr];
    NSDictionary *parDic = @{
                             @"pickuptype":_isPickInstore,
                             @"pickupstoreid":_detailCarModel.storeid,
                             
                             @"couponno":[HelpObject changeNull:_trySelDriveQuanModel.couponno],
                             @"verifycode":[HelpObject changeNull:_trySelDriveQuanModel.verifycode],
                             
                             @"ordertype":@"1",
                             @"businesstype":@"3",
                             @"orderdate":currentDateStr,
                             @"returntype":@"1",
                             @"storeid":_detailCarModel.storeid,
                             @"returnstoreid":_detailCarModel.storeid,
                             @"brandid":_detailCarModel.brandid,
                             @"seriesid":_detailCarModel.seriesid,
                             @"reservedays":_selDateModel.timeDurationStr,
                             @"carid":_detailCarModel.carid,
                             @"planpickuptime":startTimeStr,
                             @"planreturntime":endTimeStr,
                             @"pickuptype":@"1",
                             @"updateuserid":[AppSetting shareAppSetting].memberid
                             };
    __weak typeof(self) weakSelf = self;
    [self progressHUDShowWithText:nil];
    [NetWorkRequest postNetRequestData:OrderCalc parmeters:parDic response:^(NSDictionary *response) {
        if (response) {
            [weakSelf progressHUDHideImmediately];
            weakSelf.yuDingDetailModel = [TDYuDingDetailModel yy_modelWithJSON:response[@"data"]];
            weakSelf.yuDingDetailModel.planpickuptimeShow = [[YXDateHelpObject manager] getStrDateFromStrDate:weakSelf.yuDingDetailModel.planpickuptime OldFormat:@"yyyy-MM-dd HH:mm:ss" ByNewFormat:@"MM月dd日 HH:mm"];
            weakSelf.yuDingDetailModel.planreturntimeShow = [[YXDateHelpObject manager] getStrDateFromStrDate:weakSelf.yuDingDetailModel.planreturntime OldFormat:@"yyyy-MM-dd HH:mm:ss" ByNewFormat:@"MM月dd日 HH:mm"];
            
            weakSelf.lbe_basePrice.text = [NSString stringWithFormat:@"¥ %@ %@天",weakSelf.yuDingDetailModel.totalpayamount,weakSelf.yuDingDetailModel.reservedays];
            [weakSelf getAllMessageNet];
        }else {
            [weakSelf progressHUDHideImmediately];
        }
    } netError:^(NSError *error) {
        [weakSelf progressHUDShowWithCompleteText:nil isSucceed:NO];
    }];
}

- (void)getAllMessageNet {
    // MARK: - 登录操作--------------
    NSDictionary *dic = @{};
    __weak typeof(self) weakSelf = self;
    [NetWorkRequest postNetRequestData:GetMemberMessage parmeters:dic response:^(NSDictionary *response) {
        if (response) {
            //保存数据---进行一系列的操作----------
            [AppSetting shareAppSetting].photo = response[@"data"][@"photo"];
            [AppSetting shareAppSetting].updatetime = response[@"data"][@"updatetime"];
            
            weakSelf.shareMineInfoModel = [TBRMineModel yy_modelWithJSON:response[@"data"]];

            [weakSelf.tableView reloadData];
        }else {
            [weakSelf progressHUDHideImmediately];
        }
    } netError:^(NSError *error) {
        [weakSelf progressHUDShowWithCompleteText:@"获取个人信息失败" isSucceed:NO];
    }];
}




@end
